import path from 'path';
import Utils from './utils';
import Config from '../config';

const proxyUrlReg=/^\w+:\/\//i;

const proxyRulesParser = (req,res,callback)=> {

	const HOST = req.headers.host;
	const proxyRules = Config.proxyRules;
	let proxyRule = null;

    if (Utils.getArgtype(proxyRules)!='array') {
      let msg='[Config.proxyRules] an array excepted !';
      console.log(Utils.Chalk.red(msg));
      res.end(msg);
      return false;
    };
    if (!proxyRules.length) {
      let msg='[Config.proxyRules] empty unexcepted !';
      console.log(Utils.Chalk.red(msg));
      res.end(msg);
      return false;
    };
    for(let i=0;i<proxyRules.length;i++){
      let proxyHost=proxyRules[i].host;
      let proxyTarget=proxyRules[i].proxyTarget;
      proxyTarget=Utils.getArgtype(proxyTarget)=='function'?proxyTarget(req,res):proxyTarget;
      /*
      * convert proxyHost to RegExp to match HOST
      */
      if (Utils.getArgtype(proxyHost)=='string') {
        proxyHost=Utils.toRegExp(proxyHost);
      };
      if (Utils.getArgtype(proxyHost)=='regexp'&&proxyHost.test(HOST)) {
        if (proxyTarget) {
          proxyRule=proxyRules[i];
        }
        break;
      };
    }
    if (proxyRule) {
    	/*
		* separate two main type about proxyTarget
		* proxyType : 1  protocol and host maybe with path
		* proxyType : 2  local dir path
    	*/
    	let target=Utils.getArgtype(proxyRule.proxyTarget)=='function'?
	               proxyRule.proxyTarget(req,res):
	               proxyRule.proxyTarget;
	    console.log(Utils.Chalk.yellow('[Config.proxyTarget]:'));
	    console.log(Utils.Chalk.yellow('if proxyTarget is a host maybe with path,then protocol is excepted !'));
	    if (proxyUrlReg.test(target)) {
	    	proxyRule.proxyType=1;
	    }else{
	    	proxyRule.proxyType=2;
	    	target=path.resolve(process.cwd(),target);
	    };
	    proxyRule.proxyTarget=target;

    };
    
    callback&&callback(proxyRule);
}

export default proxyRulesParser;